<template>
    <el-container>
        <el-header style="height:auto;">
            <BlogsHead></BlogsHead>
        </el-header>
    </el-container>
    <div style="display: flex; justify-content: center;">
        <div id="vditorContainer" style="margin-left: 5%;"></div>
        <div style="margin-top: 5%;">
            <el-space direction="vertical" :size=30>
                <el-button type="primary" @click="UpdateBlog" style="margin-left: 60%;">修改博客</el-button>
            </el-space>
        </div>
    </div>

    <!-- <el-dialog v-model="blogPubnishVisible" title="发布博客" width="600">
        <div style="display:flex;">
            <el-text class="mx-1">博客标题：</el-text>
            <el-input v-model="blogName" style="width: 240px" placeholder="Please input" />
        </div>
        <div style="display:flex;margin-top: 5%;">
            <el-text class="mx-1">博客摘要：</el-text>
            <el-input v-model="blogBrief" style="width: 240px" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                placeholder="Please input" />
        </div>
        <div style="display:flex; margin-top: 5%;">
            <el-text class="mx-1">添加标签：</el-text>
            <el-select v-model="tagsValue" multiple placeholder="Select" style="width: 240px">
                <el-option v-for="item in tagsOptions" :key="item.id" :label="item.value" :value="item" />
            </el-select>
        </div>
        <el-button type="primary" @click="Add" style="margin-top: 5%;margin-left: 30%">发布</el-button>
    </el-dialog> -->


</template>

<script setup>
import BlogsHead from '@/components/Blogs/BlogsHead.vue';
import { IsLoginIn } from '@/components/functions/IsLoginIn.vue';
import Vditor from 'vditor';
import "vditor/dist/index.css";
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router'; // 引入路由
import { useRoute } from 'vue-router'; // 引入路由
import axios from 'axios'

const router = useRouter();
const route = useRoute();

const tagsValue = ref([])

const blogName = ref('')

const tagsOptions = ref([])

const blogBrief = ref('');

const blogPubnishVisible = ref(false);

const tagLabel = ref([]);

const blogId = ref(route.query.id);

let vditor;

function Print() {
    for (var i = 0; i < tagsValue.value.length; i++) {
        console.log(tagsValue.value[i].label);
        tagLabel.value.push(tagsValue.value[i].label);
    }
    console.log(tagLabel.value);
}

function GetTags() {
    axios
        .post('/api/tag/getAllTags')
        .then(response => {
            console.log(response);
            // console.log(localStorage.getItem('userToken'));
            // blogData = response.data.data.content;
            // console.log(blogData);
            // vditor.setValue(blogData);
            for (let i = 0; i < response.data.data.length; i++) {
                tagsOptions.value.push({ value: response.data.data[i].tagName, label: response.data.data[i].id })
            }
            console.log(tagsOptions.value);
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
}

function Add() {
    console.log(vditor.getValue());
    for (var i = 0; i < tagsValue.value.length; i++) {
        // console.log(tagsValue.value[i].label);
        tagLabel.value.push(tagsValue.value[i].label);
    }
    axios
        .post('/api/blog/add', {
            content: vditor.getValue(),


        }, {
            headers: {
                'HOSHINO_T_KK': localStorage.getItem('userToken'),
            }
        })
        .then(response => {
            console.log(response);
            console.log(localStorage.getItem('userToken'));
            // blogData = response.data.data.content;
            // console.log(blogData);
            // vditor.setValue(blogData);
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
}

function UpdateBlog() {
    axios
        .post('/api/blog/update', {
            content: vditor.getValue(),
            blog_name: blogName.value,
            blog_id: route.query.id

        }, {
            headers: {
                'HOSHINO_T_KK': localStorage.getItem('userToken'),
            }
        })
        .then(response => {
            console.log(response);
            if (response.data.data == 1) {
                window.alert("修改成功！");
                router.push('/');
            }
            // console.log(localStorage.getItem('userToken'));
            // blogData = response.data.data.content;
            // console.log(blogData);
            // vditor.setValue(blogData);
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
}

function GetBlogContent() {
    axios
        .post('/api/blog/getById', {
            blog_id: 20,
        }, {
            headers: {
                'HOSHINO_T_KK': localStorage.getItem('userToken'),
            }
        })
        .then(response => {
            console.log(response);
            blogName.value = response.data.data.blogName;

            // blogData.value = response.data.data;
            // console.log(blogData.value.tags);
            // // vditor.value.setValue(blogData.value.content.toString());
            // setTimeout(() => {
            //     vditor.value.setValue(blogData.value.content.toString());
            // }, 500);
        })
        .catch(function (error) { // 请求失败处理
            console.log(error);
        });
}

const IOptions = {
    cdn: "https://s4.zstatic.net/npm/vditor/",
    rtl: false,
    cache: {
        enable: false,
    },
    classes: {
        preview: "",
    },
    comment: {
        enable: false,
    },
    counter: {
        enable: false,
        type: "markdown",
    },
    customRenders: [],
    debugger: false,
    fullscreen: {
        index: 90,
    },
    height: "auto",
    hint: {
        delay: 200,
        emoji: {
            "+1": "👍",
            "-1": "👎",
            "confused": "😕",
            "eyes": "👀️",
            "heart": "❤️",
            "rocket": "🚀️",
            "smile": "😄",
            "tada": "🎉️",
        },
        // emojiPath: `${Constants.CDN}/dist/images/emoji`,
        extend: [],
        parse: true,
    },
    icon: "ant",
    lang: "zh_CN",
    mode: "ir",
    outline: {
        enable: true,
        position: "left",
    },
    placeholder: "请输入内容",
    preview: {
        actions: ["desktop", "tablet", "mobile", "mp-wechat", "zhihu"],
        delay: 1000,
        // hljs: Constants.HLJS_OPTIONS,
        // markdown: Constants.MARKDOWN_OPTIONS,
        // math: Constants.MATH_OPTIONS,
        maxWidth: 800,
        mode: "both",
        // theme: Constants.THEME_OPTIONS,
        render: {
            media: {
                enable: true,
            }
        }
    },
    link: {
        isOpen: true,
    },
    image: {
        isPreview: true,
    },
    resize: {
        enable: false,
        position: "bottom",
    },
    upload: {
        accept: 'image/*,.mp3, .wav, .rar',
        token: localStorage.getItem('userToken'),
        url: '/api/file/upload',
        fieldName: "files",
        linkToImgUrl: '/api/file/upload',
        filename(name) {
            console.log("filename:" + name);
            return name.replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '').
                replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, '').
                replace('/\\s/g', '')
        },
        multiple: false,
        headers: {
            'HOSHINO_T_KK': localStorage.getItem('userToken'),
        },
        format: function (files, res) {
            // 观察一下返回的数据结构
            console.log("files: " + files);
            console.log("res: " + res);

            return JSON.stringify({
                "msg": res.msg,
                "code": res.status,
                "data": {
                    "errFiles": [],
                    "succMap": {
                        "filename": res.data,
                    }
                }
            });
        },
        //粘贴图片回显处理，如果有图片加了防盗链，则让后台代理替换成自己的图片
        linkToImgFormat(files) {
            console.log(files);
            let code = 0
            let msg = ''
            let data = JSON.parse(files)
            // let linkImgName = data.result.path
            // //上传图片请求状态
            if (data.ret_code == 200) {
                let responseData = self.gb.imgOutLinkPath(data.result.path)
                let succUrl = {}
                let originalURL = 'originalURL'
                let url = 'url'
                succUrl[originalURL] = data.result.originalURL
                succUrl[url] = responseData
                let end = JSON.stringify({
                    msg,
                    code,
                    data: succUrl
                })
                return end
            } else {
                self.$message({
                    message: '图片上传失败！',
                    type: 'error'
                })
            }
        },
        //上传图片回显处理
        format(files, responseText) {

            console.log(files);
            console.log(responseText);
            let response = JSON.parse(responseText);
            let fileName = files[0].name;
            let path = response.data.succMap[fileName];
            let msg = + response.msg;
            let code = response.code;
            console.log(code);
            // vditor.insertValue('![' + fileName + ']');
            // vditor.insertValue('(' + path + ')');
            // setTimeout(() => {
            //     vditor.insertValue(' ');
            // }, 500);
            return JSON.stringify({
                msg,
                code,
                data: {
                    errFiles: [],
                    succMap: {
                        [fileName]: path
                    }
                }

            });
        },
    },
    theme: "classic",
    toolbar: [
        "emoji",
        "headings",
        "bold",
        "italic",
        "strike",
        "link",
        "|",
        "list",
        "ordered-list",
        "check",
        "outdent",
        "indent",
        "|",
        "quote",
        "line",
        "code",
        "inline-code",
        "insert-before",
        "insert-after",
        "|",
        "upload",
        "record",
        "table",
        "|",
        "undo",
        "redo",
        "|",
        "fullscreen",
        "edit-mode",
        {
            name: "more",
            toolbar: [
                "both",
                "code-theme",
                "content-theme",
                "export",
                "outline",
                "preview",
                "devtools",
                "info",
                "help",
            ],
        },
    ],
    toolbarConfig: {
        hide: true,
        pin: true,
    },
    typewriterMode: true,
    undoDelay: 800,
    // upload: {
    //     extraData: {},
    //     fieldName: "file[]",
    //     filename: (name: string) => name.replace(/\W/g, ""),
    //     linkToImgUrl: "",
    //     max: 10 * 1024 * 1024,
    //     multiple: true,
    //     url: "",
    //     withCredentials: false,
    // },
    value: "## 早上好",
    width: "70%",
    // after: () => {
    //     that.vditor.insertValue("# 插入数据")
    //     //that.vditor.setValue("# 覆盖数据")

    // }
}

onMounted(() => {
    IsLoginIn();
    vditor = new Vditor('vditorContainer', IOptions);
    GetTags();
    GetBlogContent();
})
</script>

<style scoped>
#vditor :deep(.vditor-outline) {
    display: block !important;

}

#vditor :deep(.vditor-sv) {
    display: none !important;
}
</style>
